﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Negoci = DeltaFlex.Negoci;
using DeltaFlex.Eines;

using Eines = DeltaFlex.Eines;
using System.Configuration;
using System.IO;
using System.Globalization;

namespace Vista.Privat
{
    public partial class Albaran : Page
    {
        #region Variables amb ViewState

        public Negoci.Client Client
        {
            get
            {
                object result = Session["_client"];
                if (result == null) result = null;
                return (Negoci.Client)result;
            }
            set { Session["_client"] = value; }
        }

        public Negoci.MaquinaCartoner Maquina
        {
            get
            {
                object result = Session["_maquina"];
                if (result == null) result = null;
                return (Negoci.MaquinaCartoner)result;
            }
            set { Session["_maquina"] = value; }
        }

        public DateTime? DataInici
        {
            get
            {
                return (ViewState["_dataInici"] == null ?
                   (Nullable<DateTime>)null : Convert.ToDateTime(ViewState["_dataInici"]));
            }
            set { ViewState["_dataInici"] = value; }
        }

        public DateTime? DataFi
        {
            get
            {
                return (ViewState["_dataFi"] == null ?
                   (Nullable<DateTime>)null : Convert.ToDateTime(ViewState["_dataFi"]));
            }
            set { ViewState["_dataFi"] = value; }
        }

        public List<Negoci.Albara> lstAlbara
        {
            get
            {
                return (ViewState["_lstAlbara"]) == null ? 
                    new List<Negoci.Albara>() : (List<Negoci.Albara>)ViewState["_lstAlbara"];
            }
            set {ViewState["_lstAlbara"]=value;}
        }

        public int NextIdFactura
        {
            get
            {
                return Convert.ToInt32(ViewState["_nextIdFactura"]) == 0 ?
                  0 : Convert.ToInt32(ViewState["_nextIdFactura"]);
            }
            set { ViewState["_nextIdFactura"] = value; }
        }

        public decimal  TotalBrut
        {
            get
            {
                return Convert.ToDecimal(ViewState["_totalBrut"]) == 0 ?
                  0 : Convert.ToDecimal(ViewState["_totalBrut"]);
            }
            set { ViewState["_totalBrut"] = value; }
        }

        public decimal Descompte
        {
            get
            {
                return Convert.ToDecimal(ViewState["_descompte"]) == 0 ?
                  0 : Convert.ToDecimal(ViewState["_descompte"]);
            }
            set { ViewState["_descompte"] = value; }
        }

        public decimal BaseImponible
        {
            get
            {
                return Convert.ToDecimal(ViewState["_baseImponible"]) == 0 ?
                  0 : Convert.ToDecimal(ViewState["_baseImponible"]);
            }
            set { ViewState["_baseImponible"] = value; }
        }

        public decimal IVA
        {
            get
            {
                return Convert.ToDecimal(ViewState["_iva"]) == 0 ?
                  0 : Convert.ToDecimal(ViewState["_iva"]);
            }
            set { ViewState["_iva"] = value; }
        }

        public decimal TotalIVA
        {
            get
            {
                return Convert.ToDecimal(ViewState["_totaliva"]) == 0 ?
                  0 : Convert.ToDecimal(ViewState["_totaliva"]);
            }
            set { ViewState["_totaliva"] = value; }
        }

        public decimal TotalFactura
        {
            get
            {
                return Convert.ToDecimal(ViewState["_totalFactura"]) == 0 ?
                  0 : Convert.ToDecimal(ViewState["_totalFactura"]);
            }
            set { ViewState["_totalFactura"] = value; }
        }

        public DateTime Venciment
        {
            get
            {
                return (ViewState["_venciment"] == null ?
                   DateTime.Today : Convert.ToDateTime(ViewState["_venciment"]));
            }
            set { ViewState["_venciment"] = value; }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        #region Buscar Albarà
        protected void btnCercarAlbara_Click(object sender, EventArgs e)
        {
            Client = Negoci.Client.LlistarClientByIDClient(Convert.ToInt32(ddlClient.SelectedValue))[0];
            DataInici = txtDataIni.Text == string.Empty ? Convert.ToDateTime("01/01/1950 0:00:00") : Convert.ToDateTime(txtDataIni.Text);
            DataFi = txtDataFi.Text == string.Empty ? Convert.ToDateTime("01/01/3000 0:00:00") : Convert.ToDateTime(txtDataFi.Text);
            
            lstAlbara = Negoci.Albara.LlistarAlbarans(Client.IdClient, null, DataInici, DataFi);

            gvAlbarans.DataSource = lstAlbara;
            gvAlbarans.DataBind();

            btnCrearFactura.Visible = true;
            lblDescompte.Visible = true;
            txtDescompte.Visible = true;
            lblIVA.Visible = true;
            txtIVA.Visible = true;
            lblVenciment.Visible = true;
            txtVenciment.Visible = true;
            upBuscarAlbara.Update();
        }
        #endregion

        #region Crear Factura
        protected void btnCrearFactura_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in gvAlbarans.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    CheckBox chkRow = (row.Cells[0].FindControl("chkAlbara") as CheckBox);
                    if (!chkRow.Checked)
                    {
                        lstAlbara.RemoveAll(i => i.IdAlbara.Equals(Convert.ToInt32(row.Cells[1].Text)));
                    }
                }
            }
            CalcularTotalFactura();
        }

        private void CalcularTotalFactura()
        {
            foreach (Negoci.Albara albara in lstAlbara)
                TotalBrut += albara.ImportTotal;

            Descompte = string.IsNullOrEmpty(txtDescompte.Text) ? (decimal)0 : Convert.ToDecimal(txtDescompte.Text);
            IVA = string.IsNullOrEmpty(txtIVA.Text) ? (decimal)21 : Convert.ToDecimal(txtDescompte.Text);

            if (Descompte > 0)
                BaseImponible = decimal.Subtract(TotalBrut, decimal.Divide(decimal.Multiply(TotalBrut, Descompte), 100));
            else
                BaseImponible = TotalBrut;

            TotalIVA = decimal.Divide(decimal.Multiply(BaseImponible, IVA), 100);

            TotalFactura = BaseImponible + TotalIVA;

            Venciment = string.IsNullOrEmpty(txtVenciment.Text) ? DateTime.Today.AddDays(30) : Convert.ToDateTime(txtVenciment.Text);

            GuardarFactura();
        }

        /// <summary>
        /// Guarda una factura a BD
        /// </summary>
        private void GuardarFactura()
        {
            NextIdFactura = Negoci.Factura.Cercar_NextIdFactura();
            string exepcio = string.Empty;
            string missatge = string.Empty;

            try
            {
                foreach (Negoci.Albara albara in lstAlbara)
                    Negoci.Concepte_Factura.InsertarConcepte_Factura(NextIdFactura, albara.IdAlbara);
            }
                catch (Exception ex)
            {
                exepcio = "Error en guardar els conceptes de la Factura: '" + NextIdFactura + "' <br/> " + ex.Message;
            }

            try
            {
                Negoci.Factura.InsertarFactura(NextIdFactura, Client.IdClient,DateTime.Today, Venciment, TotalFactura);
            }
            catch (Exception ex)
            {
                exepcio = "Error en guardar la Factura: '" + NextIdFactura + "' <br/> " + ex.Message;
            }

            if (String.IsNullOrEmpty(exepcio))
            {
                missatge = ConstantsAlbara.mplbGuardarFacturaOK;
                ImprimirFactura();
            }
            else
                missatge = ConstantsAlbara.mplbGuardarFacturaKO + " <br/> " + exepcio;

            mpAlbara.LabelHeader = ConstantsAlbara.mplhGuardarFactura;
            mpAlbara.LabelBody = missatge;
            mpAlbara.MostraInfo = true;

            mpAlbara.MostrarModal();
                       
        }

        /// <summary>
        /// Imprimeix una factura en PDF
        /// </summary>
        private void ImprimirFactura()
        {
            #region Inicialització i estils
            PDFManager pdf = new PDFManager();
            pdf.EmptyLineHeight = 5;
            pdf.Margin = 32;

            PDFTextStyle styleHeaderTitle = new PDFTextStyle(Eines.FontSize.xsmall, Eines.TextAlign.Center, true, false, false);
            PDFTextStyle styleBodyTitle = new PDFTextStyle(Eines.FontSize.xxsmall, Eines.TextAlign.Left, true, false, false);
            PDFTextStyle styleBodyTitleR = new PDFTextStyle(Eines.FontSize.xxsmall, Eines.TextAlign.Right, true, false, false);
            PDFTextStyle styleBodyNormalLeft = new PDFTextStyle(Eines.FontSize.xxsmaller, Eines.TextAlign.Left, false, false, false);
            PDFTextStyle styleBodyNormalRight = new PDFTextStyle(Eines.FontSize.xxsmaller, Eines.TextAlign.Right, false, false, false);
            PDFTextStyle styleBodyNormalCenter = new PDFTextStyle(Eines.FontSize.xxsmaller, Eines.TextAlign.Center, false, false, false);

            string logoPath = Server.MapPath("~/Imatges/logoAlbaran.jpg");

            PDFDocument doc = new PDFDocument();
            #endregion

            #region Capçalera
            doc.Header = new PDFHeader(new PDFText("", styleHeaderTitle),
                                       new PDFImage(logoPath),
                                       false,
                                       50);

            doc.Header.UseRealHeight = false;
            #endregion

            #region Cos
            doc.Body = new PDFBody();

            List<IPDFElement> elements;
            
            // Data
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("Fecha: " + DateTime.Today.ToShortDateString(), styleBodyNormalRight));
            elements.Add(new Eines.PDFText("Vencimiento: " + Venciment, styleBodyNormalRight));
            doc.Body.Rows.Add(new Eines.PDFRow(elements));

            // Títul
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("Factura", styleBodyTitle));
            elements.Add(new Eines.PDFText("Proveedor", styleBodyTitleR));
            doc.Body.Rows.Add(new Eines.PDFRow(elements));

            // Línia
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFLine(LineWidth.Half));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "100", 0));

            // Informació de Factura i Proveedor
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("Factura nº: " + NextIdFactura, styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("Nº Cliente: " + Client.IdClient, styleBodyNormalRight));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "11", 0));

            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("Dirección: Pol.Ind. Cataluña Sud", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("Cliente: " + Client.NomClient + " - " + Client.NifClient, styleBodyNormalRight));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "11", 0));

            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("              " + "parcela 24.4", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(Client.AdreçaClient.CarrerNumero + " " + Client.AdreçaClient.Poligon, styleBodyNormalRight));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "11", 0));

            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("              " + "43500 Tortosa", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(Client.AdreçaClient.Ciutat + " " + Client.AdreçaClient.CodiPostal, styleBodyNormalRight));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "11", 0));

            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("NIF: J55633861", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(Client.AdreçaClient.Provincia + " (" + Client.AdreçaClient.Pais + ")", styleBodyNormalRight));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "11", 0));

            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("Forma de pago: " + Client.FormaPago, styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(Client.TelefonClient.ToString(), styleBodyNormalRight));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "11", 0));

            // Espai en blanc
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText(string.Empty));
            doc.Body.Rows.Add(new Eines.PDFRow());

            // Doble Línia
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFLine(LineWidth.Double));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "100", 0, 10));

            // Espai en blanc
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText(string.Empty));
            elements.Add(new Eines.PDFText(string.Empty));
            doc.Body.Rows.Add(new Eines.PDFRow());

            // Doble Línia
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFLine(LineWidth.Double));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "100", 0, 10));

            // Conceptes Factura

            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("|Nº Albaran", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|Nº Pedido", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|Nº Codigo", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|Descripcion", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|Fecha", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|Importe", styleBodyNormalLeft));
            doc.Body.Rows.Add(new Eines.PDFRow(elements));

            // Linia
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFLine(LineWidth.Half));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "100", 0, 10));

            // Llistat d'albarans que es volen facturar
            foreach (Negoci.Albara albara in lstAlbara)
            {
                elements = new List<IPDFElement>();
                elements.Add(new Eines.PDFText(albara.IdAlbara.ToString(), styleBodyNormalLeft));
                elements.Add(new Eines.PDFText(albara.OrdreTreball.PedidoClient, styleBodyNormalLeft));
                elements.Add(new Eines.PDFText(" ", styleBodyNormalLeft));
                elements.Add(new Eines.PDFText(albara.OrdreTreball.IdTreball, styleBodyNormalLeft));
                elements.Add(new Eines.PDFText(albara.Data.ToString("dd-mm-yyyy"), styleBodyNormalLeft));
                elements.Add(new Eines.PDFText(albara.ImportTotal.ToString("C2", CultureInfo.CurrentCulture), styleBodyNormalLeft));
                doc.Body.Rows.Add(new Eines.PDFRow(elements));

            }

            // Espai en blanc
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText(string.Empty));
            elements.Add(new Eines.PDFText(string.Empty));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, 100));

            // Línia
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFLine(LineWidth.Half));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "100", 0));

            // Suma total de sota
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText("|TOTAL BRUTO", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|% DESC ", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|BASE IMP.", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|% IVA", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|TOTAL IVA", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText("|TOTAL", styleBodyNormalLeft));
            doc.Body.Rows.Add(new Eines.PDFRow(elements));

            // Línia
            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFLine(LineWidth.Half));
            doc.Body.Rows.Add(new Eines.PDFRow(elements, "100", 0));

            elements = new List<IPDFElement>();
            elements.Add(new Eines.PDFText(TotalBrut.ToString("C2", CultureInfo.CurrentCulture), styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(Descompte.ToString() + "%", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(BaseImponible.ToString("C2", CultureInfo.CurrentCulture), styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(IVA.ToString() + "%", styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(TotalIVA.ToString("C2", CultureInfo.CurrentCulture), styleBodyNormalLeft));
            elements.Add(new Eines.PDFText(TotalFactura.ToString("C2", CultureInfo.CurrentCulture), styleBodyNormalLeft));
            doc.Body.Rows.Add(new Eines.PDFRow(elements));
                       
            #endregion

            #region Peu
            List<string> lstTextPeu = new List<string>();
            lstTextPeu.Add("Observaciones del cliente");
            lstTextPeu.Add("Pol.Ind. Cataluña Sud");
            lstTextPeu.Add("parcela 24.4");
            lstTextPeu.Add("43500 Tortosa");
            lstTextPeu.Add("Tarragona (España)");
            lstTextPeu.Add("DeltaFlex, S.C.P.- J55633861");

            doc.Footer = new PDFFooter(true, lstTextPeu, styleBodyTitle);

            #endregion

            #region Finalització

            pdf.Documentos.Add(doc);

            string nomFitxer = "Factura " + DateTime.Today.ToString("dd-mm-yyyy") + ".pdf";
            
            string pathPDF = Server.MapPath(ConfigurationManager.AppSettings["pathTMP"]) + nomFitxer;

            if (File.Exists(pathPDF))
                File.Delete(pathPDF);

            pdf.CrearPDF(Server.MapPath(ConfigurationManager.AppSettings["pathTMP"]), nomFitxer, "Factura");

            FileStream file = File.Open(pathPDF, FileMode.Open, FileAccess.Read);

            BinaryReader br = new BinaryReader(file);
            byte[] dades = new byte[(int)file.Length];
            br.Read(dades, 0, (int)file.Length);
            br.Close();
            file.Close();

            if (File.Exists(pathPDF))
                File.Delete(pathPDF);

            if (dades != null)
            {
                Response.ContentType = "application/pdf";
                Response.AppendHeader("content-length", dades.Length.ToString());
                Response.AppendHeader("content-disposition", "attachment; filename=" + nomFitxer);
                Response.BinaryWrite(dades);
                Response.End();
            }

            #endregion
        }
        #endregion

        #region Operacions Grids
        protected void gvAlbarans_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // Carregar Albarà i editar-lo
            if (e.CommandName.Equals(ConstantsAlbara.EDITAR))
            {
                int idAlbara = Convert.ToInt32(e.CommandArgument);

                Session["_EditAlbara"] = lstAlbara.FirstOrDefault(i => i.IdAlbara.Equals(idAlbara));

                Response.Redirect(Request.ApplicationPath + ConstantsGlobals.URLEditarAlbara);
            }

           
        }
        #endregion
        
    }
}